%% the base send to all asking for 
% load 'training.mat';
%%
serialPortId = '/dev/tty.usbserial-FTFO9L12';% '/dev/tty.usbserial-FTFO9HPY';
serialPort = serial(serialPortId, 'BaudRate', 9600, 'DataBits', 8, 'Timeout', 1.5);
% Open Serial Port
try
    fopen(serialPort);
catch ME
    error('failed to open serial port');
end
areaID = 1;
    
while 1
    % get area id
    cmd = input('collecting area: (1~4, 0 quit)');

    if cmd == 0
        break;
    else
        areaID = cmd;
    end
    
    % init
    trainingSet{areaID} = [];
    i = 1;
    rxInfo = [];
    
    % get 20 readings at one point
    while i < 20
        rxInfo = [rxInfo fscanf(serialPort)];

        if length(rxInfo) > 10 
            % get information from serial port msg
            info = textscan(rxInfo, '%d,%d,%d,%d,%d,%d,%d')
            rxInfo = [];
            fprintf('area: %d, num: %d, sig: %d,%d,%d,%d,%d\r\n'...
                ,areaID, i+1, info{3},info{4},info{5},info{6},info{7});
            
            if info{1} == 2 & info{2} == 2 ...
                    & sum(ismember([info{3},info{4},info{5},info{6},info{7}], -1)) == 0
                % check the validation of the signature readings
                valid = true;
                for j = 3 : 7
                    if info{j} > -9 | info{j} < -91
                        valid = false;
                        break;
                    end
                end
                
                if valid
                    trainingSet{areaID} = [trainingSet{areaID}; ...
                        info{3},info{4},info{5},info{6},info{7}]; 
                    i = i + 1;
                end
            end
        end

    end
    
end
    
save ('training.mat', 'trainingSet');
% Close port
try
    flushinput(serialPort);
    flushoutput(serialPort);
    stopasync(serialPort);
    fclose(serialPort);
    delete(serialPort);
    clear serialPort;
catch ME
    error('fail to close the serial port, check connection and name'); 
end